﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.VoteManage
{
	public partial class VoteList : BasePage
	{
		private int _classId;
		private bool _isLoadClassId = false;
		/// <summary>
		/// 当前的类别标识。
		/// </summary>
		protected int ClassId
		{
			get
			{
				if (!_isLoadClassId)
				{
					if (!String.IsNullOrEmpty(Request.QueryString["ClassId"]))
						_classId = Convert.ToInt32(Request.QueryString["ClassId"]);
					_isLoadClassId = true;
				}
				return _classId;
			}
		}

		protected string VoteClassName
		{
			get { return VoteClasses.GetItem(ClassId).ClassName; }
		}

		public string EmbeddedVoteScripts
		{
			get
			{
				int identifier;
				StringBuilder sbScripts = new StringBuilder();

				foreach (RepeaterItem item in List.Items)
				{
					if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
					{
						CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
						if (!cbSelect.Checked)
							continue;
						identifier = GetListItemIdentifier(item);

						sbScripts.Append("<script type='text/javascript' language='javascript' src='/Article/EmbeddedVote.aspx?VoteID=" + identifier.ToString() + "'></script>");
					}
				}

				return sbScripts.ToString();
			}
		}


		protected void Page_Load(object sender, EventArgs e)
		{
			if (Votes.GetManageListRight(ClassId,SiteId))
			{
				if (!IsPostBack)
				{
					LoadList();
					Page.DataBind();
				}
			}
			else
			{
				Messages.Add(new PageMessage(false, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
		}

		protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
		{
			pager.CurrentPageIndex = e.NewPageIndex;
			LoadList();
		}

		protected void BtSearch_Click(object sender, EventArgs e)
		{
			pager.CurrentPageIndex = 1;
			LoadList();
		}

		protected void BtReload_Click(object sender, EventArgs e)
		{
			LoadList();
		}

		protected void List_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			int identifier = GetListItemIdentifier(e.Item);
			string messages = "";

			switch (e.CommandName)
			{
				case "Delete":
					messages = Delete(identifier);
					break;
				case "SetEffective":
					messages = SetEffectiveState(identifier);
					break;
				case "SetHomeDisplay":
					messages = SetHomeDisplay(identifier);
					break;
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		protected void BtDelete_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;

					identifier = GetListItemIdentifier(item);
					string message = Delete(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		protected void BtSeffiective_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			string messages = "";

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;
					identifier = GetListItemIdentifier(item);
					string message = SetEffectiveState(identifier);

					if (!String.IsNullOrEmpty(message))
						messages += "<li>[" + identifier.ToString() + "]" + message + "</li>";
				}
			}
			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.OperationErrorTitle, messages));
			}

			LoadList();
		}

		/// <summary>
		/// 加载列表。
		/// </summary>
		protected void LoadList()
		{
			PaginationInfo<List<Votes.VoteForManageList>> pageInfo =
				Votes.GetPaginationManageList(ClassId,IntExtensions.ParseOrNull(CtrChannelIds.SelectedValue), TbKeyword.Text, pager.PageSize, pager.CurrentPageIndex);

			pager.RecordCount = pageInfo.RecordCount;

			List.DataSource = pageInfo.Records;
			List.DataBind();

			pager.CustomInfoHTML = Helper.GetPagerCustomInfoHtml<List<Votes.VoteForManageList>>(pageInfo);
		}

		/// <summary>
		/// 取得 ListItem 的标识符。
		/// </summary>
		/// <param name="item">列表的 ListItem。</param>
		/// <returns>ListItem 的标识符。</returns>
		protected int GetListItemIdentifier(RepeaterItem item)
		{
			int identifier;
			HiddenField control;

			control = (HiddenField)item.FindControl("Identifier_VoteID");
			identifier = Convert.ToInt32(control.Value);

			return identifier;
		}

		/// <summary>
		/// 删除指定的信息
		/// </summary>
		/// <param name="identifier">要删除信息的标识符。</param>
		/// <returns>如果删除发生错误则返回错误消息。</returns>
		protected string Delete(int identifier)
		{
			if (Votes.GetDeleteRight(Votes.GetItem(identifier)))
			{
				Votes.Delete(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_DeleteAppointedObject, identifier);
		}


		/// <summary>
		/// 修改投票有效状态
		/// </summary>
		/// <param name="identifier"></param>
		/// <returns>如果发生错误则返回错误消息。</returns>
		public string SetEffectiveState(int identifier)
		{
			if (Votes.GetSetEffectiveStateRight(Votes.GetItem(identifier)))
			{
				Votes.SetEffectiveState(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}

		public string SetHomeDisplay(int identifier)
		{
			if (Votes.GetSetEffectiveStateRight(Votes.GetItem(identifier)))
			{
				Votes.SetHomeDisplay(identifier);
				return null;
			}
			else
				return string.Format(Res.PermissionException_SettingAppointedObject, identifier);
		}


		protected void BtMadeVoteScript_ServerClick(object sender, EventArgs e)
		{
			int identifier;
			StringBuilder sbVoteScript = new StringBuilder("");

			foreach (RepeaterItem item in List.Items)
			{
				if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
				{
					CheckBox cbSelect = (CheckBox)item.FindControl("CbSelect");
					if (!cbSelect.Checked)
						continue;
					identifier = GetListItemIdentifier(item);

					sbVoteScript.Append("<script type='text/javascript' language='javascript' src='/Article/EmbeddedVote.aspx?SiteId="+(SiteId.HasValue? SiteId.Value.ToString():"") +"VoteID=" + identifier.ToString() + "'></script>\r\n");
				}
			}

			string url = "PreviewEmbeddedVote.aspx?SiteId=" + (SiteId.HasValue ? SiteId.Value.ToString() : "") + "Scripts=" + Server.UrlEncode(sbVoteScript.ToString());
			ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "openPreviewEmbeddedVoteWindow", "OpenWindowCenter(\"" + url + "\");", true);
		}
	}
}
